<template>
  <div>
    <el-button type="primary" @click="openDialog()">新增打卡点</el-button>
    <el-table :data="tableData" style="width: 100%; margin-top: 16px">
      <el-table-column type="index" :index="(index) => index + 1" label="编号" width="80" />
      <el-table-column prop="aname" label="小区ID" />
      <el-table-column prop="pname" label="打卡点名称" />
      <el-table-column prop="ptype" label="类型" />
      <el-table-column prop="pdesc" label="描述" />
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button size="small" @click="openDialog(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      style="margin-top: 16px"
      background
      layout="prev, pager, next, jumper, ->, total"
      :total="total"
      :page-size="pageSize"
      :current-page="currentPage"
      @current-change="handlePageChange"
    />
    <el-dialog :title="dialogTitle" v-model="dialogVisible">
      <el-form :model="form" label-width="90px">
        <el-form-item label="小区ID">
          <el-select v-model="form.aId" placeholder="请选择小区" @change="handleCommunityChange" clearable :disabled="communitiesLoading">
            <el-option v-for="community in communities" :key="community.aId" :label="`${community.aname}`" :value="community.aId" />
          </el-select>
          <div v-if="communitiesLoading" class="el-loading-text">加载中...</div>
          <div v-if="communitiesError" class="text-danger">{{ communitiesError }}</div>
        </el-form-item>
        <el-form-item label="打卡点名称">
          <el-input v-model="form.pname" />
        </el-form-item>
        <el-form-item label="类型">
          <el-input v-model="form.ptype" />
        </el-form-item>
        <el-form-item label="位置">
          <el-input v-model="form.pdesc" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessageBox } from 'element-plus';
import { postRequest, putRequest, deleteRequest ,getRequest} from '@/utils/request';

const tableData = ref([]);
const total = ref(0);
const pageSize = ref(10);
const currentPage = ref(1);
const dialogVisible = ref(false);
const dialogTitle = ref('新增打卡点');
const form = reactive({
  id: null,
  aname: '',
  aId: '',
  pname: '',
  ptype: '',
  pdesc: ''
});
const communities = ref([]);
const communitiesLoading = ref(false);
const communitiesError = ref('');

function fetchCommunities() {
  communitiesLoading.value = true;
  communitiesError.value = '';
  getRequest('/area/getAreaLists').then(res => {
    if (res && res.data && Array.isArray(res.data.data)) {
      const validCommunities = res.data.data
        .filter(element => element && element.id !== undefined)
        .map(element => ({
          aId: String(element.id),
          aname: element.aname || element.name || `小区${element.id}`
        }));
      communities.value = validCommunities;
      if (validCommunities.length === 0) {
        communitiesError.value = '未找到小区数据，请联系系统管理员';
      }
    } else {
      communitiesError.value = '小区数据格式不正确';
      console.error('小区数据格式错误:', res);
    }
  }).catch(error => {
    communitiesError.value = '获取小区列表失败: ' + (error.message || '网络错误');
    console.error('获取小区列表失败:', error);
  }).finally(() => {
    communitiesLoading.value = false;
  });
}

function fetchData() {
  postRequest('/point/searchPointByPage', { current: currentPage.value, size: pageSize.value }).then(res => {
    if (res && res.data) {
      tableData.value = Array.isArray(res.data.data.points) ? res.data.data.points : [];
      total.value = res.data.data.total || 0;
    } else {
      tableData.value = [];
      total.value = 0;
    }
  }).catch(error => {
    console.error('获取数据失败:', error);
    tableData.value = [];
    total.value = 0;
  });
}

function openDialog(row) {
  if (row) {
    dialogTitle.value = '编辑打卡点';
    Object.assign(form, row);
    form.aId = row.aId || row.aname || '';
    form.aname = row.aname || '';
    // 手动触发选择事件以更新显示名称
    handleCommunityChange(form.aId);
  } else {
    dialogTitle.value = '新增打卡点';
    form.id = null;
    form.aname = '';
    form.aId = '';
    form.pname = '';
    form.ptype = '';
    form.pdesc = '';
  }
  dialogVisible.value = true;
}

function handleCommunityChange(aId) {
  const selectedCommunity = communities.value.find(community => community.aId === String(aId));
  if (selectedCommunity) {
    form.aname = selectedCommunity.aname;
  } else {
    form.aname = '';
    console.warn('未找到ID为', aId, '的小区');
  }
}

function handleSubmit() {
  if (form.id) {
    putRequest('/point/updatePointById', form).then(() => {
      dialogVisible.value = false;
      fetchData();
    });
  } else {
    postRequest('/point/addPoint', form).then(() => {
      dialogVisible.value = false;
      fetchData();
    });
  }
}

function handleDelete(id) {
  ElMessageBox.confirm('确定要删除该记录吗？', '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteRequest(`/point/deletePointById/${id}`).then(() => {
      fetchData();
    });
  }).catch(() => {});
}

function handlePageChange(page) {
  currentPage.value = page;
  fetchData();
}

onMounted(() => {
  fetchData();
  fetchCommunities();
});
</script>
